package hapi.receive;

import java.util.Random;

import hapi.ontology.HL7Ontology;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.Property;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.parser.EncodingNotSupportedException;
import ca.uhn.hl7v2.parser.GenericParser;
import ca.uhn.hl7v2.parser.Parser;
import ca.uhn.hl7v2.util.Terser;

public class ReceiveBehaviour extends OneShotBehaviour{

	private ACLMessage msg;
	private Agent agent;
	
	public ReceiveBehaviour(Agent agent, ACLMessage msg) {
		this.agent = agent;
		this.msg = msg;
	}
	
	@Override
	public void action() {
		//System.out.println("[Receive Behaviour]:");
		if (msg != null) {
			String ms = msg.getContent();
			//System.out.println(msg);
			try {
				Parser p = new GenericParser();
				Message hapiMsg = p.parse(ms);
				Terser terser = new Terser(hapiMsg);
				//String messageType = terser.get("/.MSH-9-1");
				String triggerEvent = terser.get("/.MSH-9-2");
				
				if(triggerEvent.equals("A01")){
					sendMens(ms, triggerEvent);
				}else if(triggerEvent.equals("A03")){
					sendMens(ms, triggerEvent);
				}else if(triggerEvent.equals("A04")){
					sendMens(ms, triggerEvent);
				}else if(triggerEvent.equals("A08")){
					sendMens(ms, triggerEvent);
				}else{
					System.out.println("Outro");
				}
				
			} catch (EncodingNotSupportedException e) {
				e.printStackTrace();
			} catch (HL7Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private void sendMens(String ms, String triggerEvent){
		DFAgentDescription dfd = new DFAgentDescription();
        ServiceDescription sd = new ServiceDescription();
        sd.setType(HL7Ontology.DATABASE_STORAGE);
        Property pro = new Property();
		pro.setName("Type");
		pro.setValue(new String(triggerEvent));
		sd.addProperties(pro);
        dfd.addServices(sd);
        try
        {
            DFAgentDescription[] result = DFService.search(agent, dfd);
            if(result.length>0){
            	ACLMessage mensagem = new ACLMessage(ACLMessage.INFORM);
            	Random rand = new Random();
            	AID r = result[rand.nextInt(result.length)].getName();
            	//System.out.println(r);
            	mensagem.addReceiver(r);
            	mensagem.setContent(ms);
            	agent.send(mensagem);			            	
            }
        }
        catch (FIPAException fe) { 
        	fe.printStackTrace(); 
        }	
	}

}
